# -*- coding:utf-8 -*-
import requests
import hashlib
import xmltodict
import time
import random
import string


class WX_PayToolUtil():
    """ 微信支付工具 """

    def __init__(self, APP_ID, MCH_ID, API_KEY, NOTIFY_URL):
        self._APP_ID = APP_ID  # 小程序ID
        self._MCH_ID = MCH_ID  # # 商户号
        self._API_KEY = API_KEY
        self._UFDODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"  # 接口链接
        self._NOTIFY_URL = NOTIFY_URL  # 异步通知

    def generate_sign(self, param):
            '''生成签名'''
            stringA = ''
            ks = sorted(param.keys())
            # 参数排序
            for k in ks:
                stringA += (k + '=' + param[k] + '&')
            # 拼接商户KEY
            stringSignTemp = stringA + "key=" + self._API_KEY
            # md5加密,也可以用其他方式
            hash_md5 = hashlib.md5(stringSignTemp.encode('utf8'))
            sign = hash_md5.hexdigest().upper()
            return sign

    def getPayUrl(self, orderid, openid, goodsPrice, attach='0', **kwargs):
        """向微信支付端发出请求，获取url"""
        key = self._API_KEY
        nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 30))  # 生成随机字符串，小于32位
        params = {
            'appid': self._APP_ID,  # 小程序ID T
            'mch_id': self._MCH_ID,  # 商户号 T
            'nonce_str': nonce_str,  # 随机字符串 T
            "body": 'Ozhas',  # 支付说明 T
            'out_trade_no': orderid,  # 生成的订单号 T
            'total_fee': str(goodsPrice),  # 标价金额 T
            'spbill_create_ip': "127.0.0.1",  # 终端IP(用户ip) F # 小程序不能获取客户ip，web用socekt实现 F
            'notify_url': self._NOTIFY_URL,  # 支付成功之后，微信异步通知(post) T
            'trade_type': "JSAPI",  # 支付类型 T
            "openid": openid,  # 用户id
            "attach": str(attach),  # 附加数据 F
            "detail": '官方联系：手机号 & 微信号：15599882233'  # 商品详情 F
         }

        # 生成签名
        params['sign'] = self.generate_sign(params)

        # python3一种写法
        param = {'root': params}
        xml = xmltodict.unparse(param)
        response = requests.post(self._UFDODER_URL, data=xml.encode('utf-8'), headers={'Content-Type': 'text/xml'})
        response.encoding = response.apparent_encoding
        # xml 2 dict
        msg = response.text
        xmlmsg = xmltodict.parse(msg)

        # 4. 获取prepay_id
        if xmlmsg['xml']['return_code'] == 'SUCCESS' and xmlmsg['xml']['result_code'] == 'SUCCESS':
            prepay_id = xmlmsg['xml']['prepay_id']
            # 时间戳
            timeStamp = str(int(time.time()))
            # 5. 五个参数
            data = {
                "appId": self._APP_ID,
                "nonceStr": nonce_str,
                "package": "prepay_id=" + prepay_id,
                "signType": 'MD5',
                "timeStamp": timeStamp,
            }

            # 6. paySign签名
            paySign = self.generate_sign(data)
            data["paySign"] = paySign  # 加入签名
            # 7. 传给前端的签名后的参数
            return data
        else:
            return xmlmsg

